Search


📜 [專欄新文章] Solidity Weekly #12
✍️ mingd...

  • Share this:


📜 [專欄新文章] Solidity Weekly #12
✍️ mingderwang
📥 歡迎投稿: https://medium.com/taipei-ethereum-meetup #徵技術分享文 #使用心得 #教學文 #medium

functions 什麼時候用 external、private、或 internal

function 跟 (storage) state 全區域合約變數預設不同,變數宣告只有在 public 才會對外開放,讓別人看得到值;而 function 剛好相反,預設是 public。也就是說你沒刻意去宣告,它是可以被外面的程式或合約呼叫。

但如果你刻意用 external、private、或 internal 來宣告 function 的被 call 的屬性,能對最佳化得到一些好處。而 public 與 external 都會讓 function 公開;相反的 internal 與 private 的 functions 只能被合約內部叫用。

限制多寡的順序是︰ public < external < internal < private。

公開 use cases︰

比如說,如果你確定不對內公開,最好宣告為 external。external 有個好處是 call 的參數是從 CALLDATA 獲得,不需要 copy 到 memory 才能執行該 function call。所以比較省 gas,尤其是處理參數是 array 時更凸顯其效果。

但用 external,自己合約如果要調用,反而要寫 this.f() 編譯器才能接受,通常是多此一舉。而且會呼叫 CALL 指令,跟 JUMP 指令比,花更多 gas。

不公開 use cases︰

當合約自己內部的 functions 不想被外部合約或程式調用,最好是用 internal 或甚至用 private 來做限制。internal 還可以被繼承的合約來調用,而 private 就只能自己合約內使用。

它們會被用 JUMP 指令來呼叫,比較省 gas。

我們用 StackOverflow 的範例來做測試,改寫成 Test.sol 如下;

// Test.sol pragma solidity^0.4.12;

contract Test {

// spend 662 gasfunction test(uint[20] a) public pure returns (uint) { return a[10] * 2; }

// spend 317 gasfunction test2(uint[20] a) external pure returns (uint) { return a[10] * 2; }

function test3(uint[20] a) internal pure returns (uint) { return a[10] * 2; } function test4(uint[20] a) private pure returns (uint) { return a[10] * 2; }}

測試程式 (DoTest.sol) 如下︰

// DoTest.solpragma solidity ^0.4.18;

import "./Test.sol";

contract DoTest is Test {uint[20] a;uint public xx;

constructor() public { a[10]=3; } function test_1() external returns(uint) { xx = test(a); return xx; } function test_2() external returns(uint) { xx = this.test2(a); // <-- use this. return xx; } function test_3() external returns(uint) { xx = test3(a); return xx; } function test_4() external returns(uint) { xx = test4(a); // <-- compile error return xx; }}

如果你用 remix 測試,會發現 DoTest 測試繼承 Test 來的不同宣告方式的 functions,會有不同的效果。且 test3() 跟 test4() 對外是看不到的。

links 分享;

Learn X in Y minutes, where X = Solidity Ming> 雖然所用的 solidity 版本 ^0.4.19 還有點舊,但註解做得很好,值得初學者參考。

Ethernaut Lvl 12 Privacy Walkthrough: How Ethereum optimizes storage to save space and be less gassy — (Nicole Zhu) Ming > Coinmonks 的 Medium 裡還有其他很多非常精彩的文章,請自己來尋寶。

The Ethernaut by Zeppelin Ming> 一個 web3/solidity 闖關遊戲平台。

Solidity Weekly #12 was originally published in Taipei Ethereum Meetup on Medium, where people are continuing the conversation by highlighting and responding to this story.

👏 歡迎轉載分享鼓掌


Tags:

About author
not provided
We have regular meeting twice per month on discussing blockchain technology, smart contracts and DApps development! We would love to have you join us!
View all posts